import {View, Text, ScrollView} from "@tarojs/components";
import {Cell, CellGroup, Empty} from "@antmjs/vantui";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {AddressModel, BoolParams} from "@/common/apis/model";
import {addressListApi, addressUpdateApi} from "@/common/apis/home_datasource";
import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import TextIcon from "@/components/TextIcon";
import BottomButton from "@/components/bottom_button";
import Taro, {usePullDownRefresh} from "@tarojs/taro";
import LogUtils from "@/utils/log";


definePageConfig({
  navigationBarTitleText: '收件地址',
  enablePullDownRefresh: true,
})
export default function AddressList() {
  const [items, setItems] = useState<AddressModel[]>()
  const isSelect = useRef(false);
  const eventChannel = useRef<Taro.EventChannel | null>();
  const getList = useCallback((isRefresh =false) => {
    addressListApi(isRefresh).then((res) => {
      if (res) {
        setItems(res)
      }
    })
  }, []);

  usePullDownRefresh(()=>{
    getList(true)
  })

  useEffect(() => {
    getList();
    const instance = Utils.getI();
    eventChannel.current = Utils.getChannel(instance)
    const params = Utils.getParamsByRouter(instance)
    if (params && params.data) {
      const p = Utils.getObjectWithUrl<BoolParams>(params.data)
      isSelect.current = p.isOk
    }
    return () => {

    }
  }, [getList]);

  const onChangeDefault = useCallback((item) => {
    if (item.isDefault === 1) return
    addressUpdateApi({
      id: `${item.id}`,
      isDefault: '1'
    }).then((res) => {
      if (res) {
        getList();
      }
    })
  }, [getList]);

  const onClickItem = useCallback((item) => {
    if (isSelect.current && eventChannel.current) {
      Utils.emit(eventChannel.current, 'selectAddress', item)
      Utils.navigateBack()
    } else {
      const url = Utils.getUrlWithObject(RouthPath.addAddress, item)
      LogUtils.info('url', url)
      Utils.navigateAndListenToEvent(url, 'addressAdded', (data) => {
        if (data) {
          getList();
        }
      })
    }
  }, [getList]);


  return (
    <View style={{display: 'flex', flexDirection: 'column', height: '100VH', backgroundColor: '#fff'}}>
      <View style={{flex: 1, overflow: 'hidden', position: 'relative'}}>
        <ScrollView style={{height: '100%', boxSizing: 'border-box'}} scrollY>
          <CellGroup>
            {items && !Utils.isEmpty(items) ? items.map((e, i) => {
              return <AddressItem item={e} isDefault={e.isDefault === 1} onChangeDefault={onChangeDefault} key={e.id}
                                  onClickItem={onClickItem}/>
            }) : <Empty description='暂无数据'/>}
          </CellGroup>

        </ScrollView>
      </View>
      <BottomButton submitText='新增地址' onSubmit={() => {
        Utils.navigateAndListenToEvent(RouthPath.addAddress, 'addressAdded', (data) => {
          if (data) {
            getList();
          }
        })


      }}
      />
    </View>
  )
}


function AddressItem(pros) {
  const item = pros.item
  return (
    <View>
      <Cell
        border={false}
        isLink
        onClick={() => {
          pros.onClickItem(item)
        }}
        renderTitle={<View style={{display: 'flex', flexDirection: 'column'}}>
          <View>
            <Text style={{color: 'black'}}>{item.recipient}</Text>
            <Text style={{color: 'gray', marginLeft: '10px'}}>{item.phone}</Text>
          </View>
          <Text style={{color: 'black'}}>{item.address}</Text>
          {
            item && pros.isDefault != null ?
              <View style={{alignSelf: 'flex-start'}}>
                <TextIcon text='设置默认' iconName='checked' iconPosition='right' iconSize='24px' textSize='14px'
                          onClick={(event) => {
                            event.stopPropagation();
                            pros.onChangeDefault(item)
                          }}
                          iconColor={pros.isDefault ? 'green' : 'grey'}
                />
              </View> : null
          }
        </View>}
      />
    </View>
  )
}

